package it.pecuswap.client.rest;

import it.pecuswap.commons.utils.ConfigurationKeys;
import it.pecuswap.configuration.Configuration;
import it.pecuswap.exceptions.ConfigurationException;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;

/**
 * Crea un client http necessario all'invocazione del servizio rest richiesto.
 * Nonostante {@link HttpClientBuilder} sia dichiaratamente NotThreadSafe, viene istanziato una volta per ogni richiesta
 * attraverso l'estensione di questa classe
 * @author Ruggiero
 *
 */
public class ClientProvider {
	
	/**
	 * Metodo generico che permette di istanziare l'interfaccia richiesta del servizio rest da invocare
	 * @param theClass classe di interfaccia del servizio
	 * @return
	 * @throws ConfigurationException 
	 */
	protected <T> T serviceClientInterfaceProvider(Class<T> theClass) throws ConfigurationException{
		
		// 1. Create AuthCache instance
		/*AuthCache authCache = new BasicAuthCache();
		 
		// 2. Generate BASIC scheme object and add it to the local auth cache
		BasicScheme basicAuth = new BasicScheme();
		authCache.put("com.bluemonkeydiamond.sippycups", basicAuth);
		 
		// 3. Add AuthCache to the execution context
		BasicHttpContext localContext = new BasicHttpContext();
		localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);*/
		 
		// 4. Create client executor and proxy
		//ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient, localContext);
		
		HttpClient httpClient = HttpClientBuilder.create().build();
		ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
		
		ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
		
		String BACKEND_URL = Configuration.getInstance().getValueOf(ConfigurationKeys.BACKEND_REST_SERVICE_URL);
		
		ResteasyWebTarget target = client.target(BACKEND_URL);
		
		T serviceClientInterface = target.proxy(theClass);
		
		return serviceClientInterface;
	}
}
